<template>
  <div class="h-full flex flex-col">
    <page-header title="维修"> </page-header>
    <div class="mt-[16px]"></div>
    <n-card class="p-4 h-full" content-style="padding: 0">
      <n-grid x-gap="10" :cols="24">
        <!-- 操作台 -->
        <n-gi :span="14">
          <!-- 搜索 -->
          <div>
            <SearchProducts
              product-type="repair"
              placeholder="搜索设备"
              v-model:value="searchKeyword"
              @pick="handlePickSearchProduct"
            />
          </div>
          <!-- 面包屑 -->
          <div class="mt-2"></div>
          <n-breadcrumb>
            <n-breadcrumb-item
              v-for="(breadCrumb, index) in breadCrumbs"
              :key="breadCrumb.key"
              @click.stop="handleClickBreanCrumb(breadCrumb, index)"
            >
              {{ breadCrumb.name }}
            </n-breadcrumb-item>
          </n-breadcrumb>
          <!-- STEPS -->
          <div class="mt-2"></div>
          <n-scrollbar :style="SCROLL_CONTAINER_STYLE">
            <!-- 选择分类 -->
            <ChooseCategory
              v-if="currentStep === RepairStepEnum.CHOOSE_CATEGORY"
              @selected="handleSelectedCategory"
            />
            <!-- 选择品牌 -->
            <ChooseBrand
              v-else-if="currentStep === RepairStepEnum.CHOOSE_BRAND"
              @selected="handleSelectedBrand"
            />
            <!-- 选择产品 -->
            <ChooseModel
              :category-id="repairForm.categoryId"
              :brand-id="repairForm.brandId"
              v-else-if="currentStep === RepairStepEnum.CHOOSE_MODEL"
              @selected="handleSelectedProduct"
            />
            <!-- 选择问题 -->
            <ChooseQuestion
              ref="chooseQuestionRef"
              :product-id="repairForm.productId"
              v-else-if="currentStep === RepairStepEnum.CHOOSE_FAULTS"
              @selected="handleConfirm"
            />
          </n-scrollbar>
        </n-gi>
        <!-- Cart -->
        <n-gi :span="10" class="flex flex-col flex-1">
          <div class="flex items-center">
            <n-select
              placeholder="请搜索选择客户"
              :loading="customerSearchLoading"
              remote
              clearable
              filterable
              :options="customersList"
              value-field="id"
              label-field="name"
              @search="handleSearchCustomer"
              v-model:value="repairForm.customerId"
            >
            </n-select>
            <n-button quaternary circle class="ml-2">
              <template #icon>
                <n-icon><PersonAdd /></n-icon>
              </template>
            </n-button>
            <n-button quaternary circle class="ml-2">
              <template #icon>
                <n-icon><CreateOutline /></n-icon>
              </template>
            </n-button>
          </div>
          <div class="mt-2"></div>
          <n-form size="small">
            <n-scrollbar :style="CART_SCROLL_CONTAINER_STYLE">
              <div v-if="repairForm.selectedQuestionList.length">
                <n-space vertical>
                  <n-card :title="repairForm.productName" size="small">
                    <n-grid x-gap="10" y-gap="10" :cols="24">
                      <n-gi :span="12">
                        <n-form-item label="序列号/IMEI" :show-feedback="false">
                          <n-input v-model:value="repairForm.sn" />
                        </n-form-item>
                      </n-gi>
                      <n-gi :span="12">
                        <n-form-item label="解锁密码" :show-feedback="false">
                          <n-input v-model:value="repairForm.pin" />
                        </n-form-item>
                      </n-gi>
                      <n-gi :span="24">
                        <n-form-item label="备注" :show-feedback="false">
                          <n-input type="textarea" />
                        </n-form-item>
                      </n-gi>
                    </n-grid>
                  </n-card>
                  <!-- 故障报价 -->
                  <n-card title="维修预估报价" size="small">
                    <n-space vertical>
                      <div
                        class="repair-question-item"
                        v-for="question in repairForm.selectedQuestionList"
                        :key="question.id"
                      >
                        <div class="flex w-full items-center">
                          <div class="content">
                            <span class="font-bold leading-[28px]">
                              {{ question.name }}
                            </span>
                            <span>
                              建议报价：
                              {{ currencyFormat(question.repairPromoPrice) }}
                            </span>
                          </div>
                          <n-button
                            strong
                            tertiary
                            size="small"
                            circle
                            type="primary"
                          >
                            <template #icon>
                              <n-icon>
                                <Trash />
                              </n-icon>
                            </template>
                          </n-button>
                        </div>
                        <div
                          class="mt-2 flex justify-between items-center"
                          v-if="question.variantId"
                        >
                          <div>
                            <n-form-item
                              size="small"
                              label="推荐部件"
                              :show-feedback="false"
                            >
                              <span>
                                {{ question.variantName }}
                              </span>
                            </n-form-item>
                          </div>
                          <!-- <div>
                            <n-form-item
                              size="small"
                              :show-feedback="false"
                              label="数量"
                            >
                              <n-input
                                size="small"
                                v-model:value="question.qty"
                              />
                            </n-form-item>
                          </div> -->
                        </div>
                      </div>
                    </n-space>
                  </n-card>
                </n-space>
              </div>
              <n-empty
                v-else
                class="mt-[20vh]"
                size="large"
                description="请选择产品"
              >
              </n-empty>
            </n-scrollbar>
          </n-form>
          <div class="mt-2">
            <n-grid x-gap="10" :cols="24">
              <n-gi :span="12">
                <n-form-item label="维修报价" :show-feedback="false">
                  <n-input v-model:value="repairForm.quotePrice" />
                </n-form-item>
              </n-gi>
              <n-gi :span="12" class="flex justify-end items-end">
                <n-button type="primary" @click.stop="handleClickCreate">
                  创建维修订单
                </n-button>
              </n-gi>
            </n-grid>
          </div>
        </n-gi>
      </n-grid>
    </n-card>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, computed } from "vue";
import { useDialog } from "naive-ui";
import { PersonAdd, CreateOutline, AddOutline, Trash } from "@vicons/ionicons5";
import { get, isEmpty } from "lodash-es";
import { Category } from "@/types/model/product/vos/category.vo";
import { Brand } from "@/types/model/product/vos/brand.vo";
import { Product } from "@/types/model/product/vos/product.vo";
import SearchProducts from "@/components/biz/searchProduct/index.vue";
import { SearchProductVO } from "@/types/model/product/vos/searchProducts.vo";
import { BreadCrumb, useBreadCrumbs } from "@/common/hooks/useBreadCrumbs";
import { useSearchCustomers } from "@/components/biz/customerModal/hooks";
import { calculatePrice, createRepairOrder } from "@/api/repair/repair.api";

import {
  RepairStepEnum,
  BreadCrumbEnmu,
  SCROLL_CONTAINER_STYLE,
  CART_SCROLL_CONTAINER_STYLE,
} from "./data";
import {
  ChooseCategory,
  ChooseBrand,
  ChooseModel,
} from "@/components/biz/choose/index";
import ChooseQuestion from "./components/chooseQuestion/index.vue";
import { currencyFormat } from "@/common/utils/currencyFormatter";

const dialog = useDialog();

const { customersList, customerSearchLoading, handleSearchCustomer } =
  useSearchCustomers();

// 怎么表示ChooseQuestion Ref
const chooseQuestionRef = ref<InstanceType<typeof ChooseQuestion> | null>(null);
const searchKeyword = ref<string>("");
const currentStep = ref<RepairStepEnum>(RepairStepEnum.CHOOSE_CATEGORY);
const isSelectedProduct = ref<boolean>(false);
const repairForm = reactive<any>({
  uuid: "",
  categoryId: "",
  categoryName: "",
  brandId: "",
  brandName: "",
  productId: "",
  productName: "",
  customerId: undefined,
  customerNote: "",
  sn: "",
  pin: "",
  quotePrice: 0,
  // {
  //     id: "", // 问题id
  //     variantId: "", // 维修部件ID
  //     variantName: "", // 维修部件名称
  //     qty: "", // 维修数量
  //   },
  selectedQuestionList: [],
});

const { breadCrumbs, addBreadItem, updateBreadIItem, clearBreadCrumbs } =
  useBreadCrumbs();

/**
 * 点击面包屑回退
 */
const handleClickBreanCrumb = (_: BreadCrumb, index: number) => {
  breadCrumbs.value = breadCrumbs.value.slice(0, index + 1);
  breadCrumbs.value[index].name = breadCrumbs.value[index].initialName;
  breadCrumbs.value[index].value = breadCrumbs.value[index].initialValue;
  currentStep.value = breadCrumbs.value[index].key as any;
};

/**
 * 选中分类
 */
const handleSelectedCategory = (payload: Category) => {
  const categoryName = get(payload, "name") || "";
  const categoryId = get(payload, "id") || "";
  repairForm.categoryId = categoryId;
  repairForm.categoryName = categoryName;
  updateBreadIItem(BreadCrumbEnmu.CATEGORY, categoryName, categoryId);
  addBreadItem(BreadCrumbEnmu.BRAND, "选择品牌", "");
  currentStep.value = RepairStepEnum.CHOOSE_BRAND;
};

/**
 * 选中产品
 * @param Product payload
 */
const handleSelectedProduct = (payload: Product) => {
  const productName = get(payload, "name") || "";
  const productId = get(payload, "id") || "";
  repairForm.productId = productId;
  repairForm.productName = productName;
  updateBreadIItem(BreadCrumbEnmu.MODEL, productName, productId);
  addBreadItem(BreadCrumbEnmu.FAULTS, "选择故障", "");
  currentStep.value = RepairStepEnum.CHOOSE_FAULTS;
};

/**
 * 选中品牌
 * @param payload
 */
const handleSelectedBrand = (payload: Brand) => {
  const brandName = get(payload, "name") || "";
  const brandId = get(payload, "id") || "";
  repairForm.brandId = brandId;
  repairForm.brandName = brandName;
  updateBreadIItem(BreadCrumbEnmu.BRAND, brandName, brandId);
  addBreadItem(BreadCrumbEnmu.MODEL, "选择产品", "");
  currentStep.value = RepairStepEnum.CHOOSE_MODEL;
};

/**
 * 选择故障后点击确定
 * @param payload
 */
const handleConfirm = async (payload: any) => {
  console.log("==== handleConfirm ====");
  console.log(payload);
  const questionList = get(payload, "checkList.questionItems") || [];
  const selectedChcekMap = get(payload, "selectedChcekMap") || {};
  if (!isEmpty(selectedChcekMap) && questionList.length) {
    let selectedQuestion = [];
    for (const key in selectedChcekMap) {
      if (selectedChcekMap[key] === "1") {
        const targetQuestion = questionList.find(
          (item: any) => item.id === key
        );
        selectedQuestion.push({
          id: key, // 问题id
          name: get(targetQuestion, "name"),
          variantId: get(targetQuestion, "variantId"), // 维修部件ID
          variantName: get(targetQuestion, "variantName"), // 维修部件名称
          repairPromoPrice: get(targetQuestion, "repairPromoPrice"), // 维修报价
          qty: 1, // 维修数量
        });
      }
    }

    if (!selectedQuestion.length) {
      dialog.warning({
        title: "温馨提示",
        content: "请选择故障",
        positiveText: "确定",
        negativeText: "取消",
      });
      return;
    }

    const params = {
      selectedQuestionIds: selectedQuestion.map((item) => item.id),
    };
    const result = await calculatePrice(params);
    console.log(result);
    repairForm.quotePrice = get(result, "result") || 0;
    repairForm.selectedQuestionList = selectedQuestion;
    isSelectedProduct.value = true;
  }
};

const resetRepairForm = () => {
  repairForm.uuid = "";
  repairForm.categoryId = "";
  repairForm.categoryName = "";
  repairForm.brandId = "";
  repairForm.brandName = "";
  repairForm.productId = "";
  repairForm.productName = "";
  repairForm.customerId = undefined;
  repairForm.customerNote = "";
  repairForm.sn = "";
  repairForm.pin = "";
  repairForm.quotePrice = 0;
  repairForm.selectedQuestionList = [];
};

const handlePickSearchProduct = (searchProduct: SearchProductVO) => {
  const { categoryId, categoryName, brandId, brandName, id, name } =
    searchProduct;
  // 1. 清空面包屑
  clearBreadCrumbs();
  // 2. 重建面包屑
  addBreadItem(BreadCrumbEnmu.CATEGORY, "选择分类", "");
  updateBreadIItem(BreadCrumbEnmu.CATEGORY, categoryName, categoryId);
  addBreadItem(BreadCrumbEnmu.BRAND, "选择品牌", "");
  updateBreadIItem(BreadCrumbEnmu.BRAND, brandName, brandId);
  addBreadItem(BreadCrumbEnmu.MODEL, "选择产品", "");
  updateBreadIItem(BreadCrumbEnmu.MODEL, name, id);
  addBreadItem(BreadCrumbEnmu.FAULTS, "选择故障", "");
  // 3. 清空repairForm
  resetRepairForm();
  repairForm.categoryId = categoryId;
  repairForm.categoryName = categoryName;
  repairForm.brandId = brandId;
  repairForm.brandName = brandName;
  repairForm.productId = id;
  repairForm.productName = name;
  currentStep.value = RepairStepEnum.CHOOSE_FAULTS;
  chooseQuestionRef.value?.refresh();
};

/**
 * 点击创建维修单
 */
const handleClickCreate = () => {
  console.log("==== handleClickCreate ====");
  console.log(repairForm);
  dialog.create({
    title: "创建维修订单",
    content: "信息确认无误？",
    negativeText: "不确认",
    positiveText: "确认",
    onPositiveClick: async () => {
      const params = {
        customerId: repairForm.customerId,
        productId: repairForm.productId,
        sn: repairForm.sn,
        pin: repairForm.pin,
        customerNote: repairForm.customerNote,
        quotePrice: repairForm.quotePrice,
        selectedQuestionList: repairForm.selectedQuestionList,
      };
      const result = await createRepairOrder(params);
      console.log(result);
      resetRepairForm();
      // 1. 清空面包屑
      clearBreadCrumbs();
      // 2. 重建面包屑
      addBreadItem(BreadCrumbEnmu.CATEGORY, "选择分类", "");
      currentStep.value = RepairStepEnum.CHOOSE_CATEGORY;
    },
  });
};

const init = () => {
  addBreadItem(BreadCrumbEnmu.CATEGORY, "选择分类", "");
};

onMounted(() => {
  init();
});
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
